package com.zdb.n1.service.impl;

import com.zdb.n1.entity.HealthData;
import com.zdb.n1.entity.User;
import com.zdb.n1.payload.response.MessageResponse;
import com.zdb.n1.repository.HealthDataRepository;
import com.zdb.n1.service.HealthDataService;
import com.zdb.n1.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Calendar;
import java.util.stream.Collectors;

@Service
public class HealthDataServiceImpl implements HealthDataService {

    @Autowired
    private HealthDataRepository healthDataRepository;

    @Autowired
    private UserService userService;

    @Override
    @Transactional
    public HealthData saveHealthData(HealthData healthData) {
        User currentUser = userService.getCurrentUser();
        healthData.setUser(currentUser);
        
        if (healthData.getRecordDate() == null) {
            healthData.setRecordDate(new Date());
        } else {
            // 处理时间格式，去除毫秒部分
            Date date = healthData.getRecordDate();
            Calendar cal = Calendar.getInstance();
            cal.setTime(date);
            cal.set(Calendar.MILLISECOND, 0);
            healthData.setRecordDate(cal.getTime());
        }
        
        return healthDataRepository.save(healthData);
    }

    @Override
    public HealthData getHealthDataById(Long id) {
        return healthDataRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("未找到健康数据记录"));
    }

    @Override
    public List<HealthData> getAllHealthDataForCurrentUser() {
        User currentUser = userService.getCurrentUser();
        List<HealthData> dataList = healthDataRepository.findByUserOrderByRecordDateDesc(currentUser);
        
        // 转换为没有懒加载关联的DTO
        return dataList.stream().map(data -> {
            HealthData dto = new HealthData();
            dto.setId(data.getId());
            dto.setRecordDate(data.getRecordDate());
            dto.setHeight(data.getHeight());
            dto.setWeight(data.getWeight());
            dto.setRestingHeartRate(data.getRestingHeartRate());
            dto.setBmi(data.getBmi());
            // 不设置user，避免懒加载问题
            return dto;
        }).toList();
    }

    @Override
    public Page<HealthData> getHealthDataForCurrentUser(Pageable pageable) {
        User currentUser = userService.getCurrentUser();
        return healthDataRepository.findByUserOrderByRecordDateDesc(currentUser, pageable);
    }

    @Override
    public List<HealthData> getHealthDataByDateRange(Date startDate, Date endDate) {
        User currentUser = userService.getCurrentUser();
        
        // 调整时间范围，确保包含整个开始日期和结束日期
        Calendar calStart = Calendar.getInstance();
        calStart.setTime(startDate);
        calStart.set(Calendar.HOUR_OF_DAY, 0);
        calStart.set(Calendar.MINUTE, 0);
        calStart.set(Calendar.SECOND, 0);
        calStart.set(Calendar.MILLISECOND, 0);
        Date startOfDay = calStart.getTime();
        
        Calendar calEnd = Calendar.getInstance();
        calEnd.setTime(endDate);
        calEnd.set(Calendar.HOUR_OF_DAY, 23);
        calEnd.set(Calendar.MINUTE, 59);
        calEnd.set(Calendar.SECOND, 59);
        calEnd.set(Calendar.MILLISECOND, 999);
        Date endOfDay = calEnd.getTime();
        

        
        List<HealthData> dataList = healthDataRepository.findByUserAndRecordDateBetweenOrderByRecordDateDesc(
                currentUser, startOfDay, endOfDay);
        

        
        // 转换为没有懒加载关联的DTO
        return dataList.stream().map(data -> {
            HealthData dto = new HealthData();
            dto.setId(data.getId());
            dto.setRecordDate(data.getRecordDate());
            dto.setHeight(data.getHeight());
            dto.setWeight(data.getWeight());
            dto.setRestingHeartRate(data.getRestingHeartRate());
            dto.setBmi(data.getBmi());
            // 不设置user，避免懒加载问题
            return dto;
        }).collect(Collectors.toList());
    }

    @Override
    public HealthData getLatestHealthData() {
        User currentUser = userService.getCurrentUser();
        return healthDataRepository.findLatestByUser(currentUser)
                .map(data -> {
                    HealthData dto = new HealthData();
                    dto.setId(data.getId());
                    dto.setRecordDate(data.getRecordDate());
                    dto.setHeight(data.getHeight());
                    dto.setWeight(data.getWeight());
                    dto.setRestingHeartRate(data.getRestingHeartRate());
                    dto.setBmi(data.getBmi());
                    // 不设置user，避免懒加载问题
                    return dto;
                })
                .orElse(null);
    }

    @Override
    @Transactional
    public MessageResponse deleteHealthData(Long id) {
        HealthData healthData = healthDataRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("未找到健康数据记录"));
        
        User currentUser = userService.getCurrentUser();
        if (!healthData.getUser().getId().equals(currentUser.getId())) {
            return MessageResponse.error("无权删除此记录");
        }
        
        healthDataRepository.delete(healthData);
        return MessageResponse.success("记录删除成功");
    }

    @Override
    public String getBmiCategory(Double bmi) {
        if (bmi == null) {
            return "未知";
        }
        
        if (bmi < 18.5) {
            return "偏瘦";
        } else if (bmi < 24.0) {
            return "正常";
        } else if (bmi < 28.0) {
            return "超重";
        } else if (bmi < 30.0) {
            return "轻度肥胖";
        } else if (bmi < 40.0) {
            return "中度肥胖";
        } else {
            return "重度肥胖";
        }
    }

    @Override
    public List<HealthData> getHealthDataByUser(User user) {
        List<HealthData> dataList = healthDataRepository.findByUserOrderByRecordDateDesc(user);
        
        // 转换为没有懒加载关联的DTO
        return dataList.stream().map(data -> {
            HealthData dto = new HealthData();
            dto.setId(data.getId());
            dto.setRecordDate(data.getRecordDate());
            dto.setHeight(data.getHeight());
            dto.setWeight(data.getWeight());
            dto.setRestingHeartRate(data.getRestingHeartRate());
            dto.setBmi(data.getBmi());
            // 设置用户ID而不是完整用户对象，避免懒加载问题
            User userRef = new User();
            userRef.setId(user.getId());
            dto.setUser(userRef);
            return dto;
        }).toList();
    }

    @Override
    @Transactional
    public HealthData updateHealthData(Long id, HealthData healthData) {
        HealthData existingData = healthDataRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("未找到健康数据记录"));
        
        // 确保ID和用户不变
        healthData.setId(id);
        healthData.setUser(existingData.getUser());
        
        // 处理时间格式，去除毫秒部分
        if (healthData.getRecordDate() != null) {
            Date date = healthData.getRecordDate();
            Calendar cal = Calendar.getInstance();
            cal.setTime(date);
            cal.set(Calendar.MILLISECOND, 0);
            healthData.setRecordDate(cal.getTime());
        }
        
        // 计算BMI
        if (healthData.getHeight() != null && healthData.getWeight() != null) {
            double heightInMeters = healthData.getHeight() / 100.0;
            double bmi = healthData.getWeight() / (heightInMeters * heightInMeters);
            healthData.setBmi(Math.round(bmi * 100.0) / 100.0);
        }
        
        return healthDataRepository.save(healthData);
    }
} 